package com.nbclass.service.impl;

import com.nbclass.domain.User;
import com.nbclass.mapper.PermissionMapper;
import com.nbclass.mapper.RoleMapper;
import com.nbclass.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/*
       AUTHOR: Jarvie -> YYDS
  CREATE TIME: 2024/9/13   
*/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.queryUserByUserName(username);
        if(user!=null){
        List<SimpleGrantedAuthority> lists=new ArrayList<>();
        //查询用户角色信息
        List<String> roleNames = roleMapper.queryRoleById(user.getUid());
            roleNames.forEach(roleName-> lists.add(new SimpleGrantedAuthority("ROLE_"+roleName)));
        //查询用户权限信息
        List<String> permissionNames = permissionMapper.queryPermissionNameByUid(user.getUid());
            permissionNames.forEach(permissionName-> lists.add(new SimpleGrantedAuthority(permissionName)));
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPwd(),lists);
        }
        return null;
    }
}
